<?php

class ApplicationController extends AbstractController
{

  public function dispatch()
  {
    return $this->forward(s::request()->route());
  }

  public function forward($route)
  {
    try {
      $this->response = new Response();

      $params = is_string($route) ? s::router()->parse($route) : $route;

      $Controller = Controller::factory($params);

      $Controller->initialize();

      $action = sy_get_param($params, 'action', 'index');

      $output = $Controller->callActionArray($action, sy_get_param($params, 'params'));

      if ($output === Response::AUTO) {
        $this->response->setLayout($Controller->getLayout());
        $this->response->setTemplate($Controller->getTemplate());

        $output = s::response()->render(false);
      }
      elseif ($output instanceof IView) {
        $output->setLayout($Controller->getLayout());

        $output = $output->render();
      }

      s::response()->output($output);

      return $output;
    }
    catch (RouterException $e) {
      s::response()->redirect404If(! DEBUG_LEVEL);
    }
    catch (ControllerNotFoundException $e) {
      s::response()->redirect404If(! DEBUG_LEVEL);
    }
    catch (ActionNotFoundException $e) {
      s::response()->redirect404If(! DEBUG_LEVEL);
    }

    throw $e;
  }

}
